import MyDrawer from "@/components/MyDrawer";
import { TopicItem } from "@/types";
import {
  enumToObject,
  ExerciseTypeEnum,
  QuestionTypeEnum,
  TopicType,
} from "@/utils/enums";
import {
  ModalForm,
  ProColumns,
  ProDescriptions,
  ProFormDigit,
  ProTable,
} from "@ant-design/pro-components";
import OperationDetail from "../topic/OperationTopic/OperationDetail";
import { Alert, Button, Form } from "antd";
import { useEffect, useMemo, useState } from "react";
import { useAsyncEffect, useRequest } from "ahooks";
import request from "@/services/interceptors";
import DownloadFile from "@/components/DownLoadFile";
import { EditFilled } from "@ant-design/icons";

export default function ExamDetail() {
  const searchParams = new URLSearchParams(window.location.search);
  const examId = searchParams.get("examId");
  const studentId = searchParams.get("studentId");
  const [examResult, setExamResult] = useState<any>({});
  const [topicList, setTopicList] = useState<TopicItem[]>([]);
  const { runAsync: examGetStudentExamDetailCreate, loading } = useRequest(
    request.sgks.examGetStudentExamDetailCreate,
    { manual: true }
  );
  const topicItemColumns: ProColumns<TopicItem>[] = [
    {
      title: "序号",
      dataIndex: "sort",
      width: "80px",
      className: "drag-visible",
    },
    {
      title: "题目编号",
      dataIndex: "code",
      hideInSearch: true,
      width: 160,
      render: (text, record) => {
        return (
          <MyDrawer
            title="操作题详情"
            drawerContent={
              record.type === TopicType.Objective ? (
                <OperationDetail exerciseId={+record?.id} />
              ) : (
                <OperationDetail exerciseId={+record?.id} />
              )
            }
          >
            <a type="link">{text}</a>
          </MyDrawer>
        );
      },
    },
    {
      title: "题目类型",
      dataIndex: "type",
      width: "80px",
      valueEnum: {
        [TopicType.Objective]: "客观题",
        [TopicType.Operation]: "操作题",
      },
    },
    {
      title: "问题类型",
      dataIndex: "questionType",
      width: "80px",
      render: (_, record) => {
        return record.type === TopicType.Objective
          ? enumToObject(QuestionTypeEnum)[record.questionType]
          : enumToObject(ExerciseTypeEnum)[record.exerciseType];
      },
    },
    {
      title: "题干",
      dataIndex: "question",
    },
    {
      title: "题目分数",
      dataIndex: "score",
      width: "80px",
      render: (_, record) => {
        return record.type === TopicType.Objective
          ? record.questionScore
          : record.exerciseScore;
      },
    },
    {
      title: "考生分数",
      dataIndex: "score",
      width: "80px",
    },
    {
      title: "考生答案",
      dataIndex: "answer",
      ellipsis: true,
      render: (_, record) => {
        return record.type === TopicType.Objective
          ? record.studentAnswer
          : record.attachment && (
              <DownloadFile text="下载" url={record.attachment} />
            );
      },
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_, record) => {
        return (
          record.type === TopicType.Operation && (
            <EditScore
              examDetailId={record.examDetailId}
              score={record.score}
              max={record.exerciseScore}
              onFinish={getExamResult}
            ></EditScore>
          )
        );
      },
    },
  ];

  const paperData = useMemo(() => {
    return topicList.map((i, index) => {
      return {
        ...i,
        sort: index + 1,
        rowKey: `${i.type}_${i.id}`,
      };
    });
  }, [topicList]);
  const getExamResult = async () => {
    const { data }: any = await examGetStudentExamDetailCreate({
      examId: +examId,
      studentId: +studentId,
    });
    setExamResult(data);
    // 设置试卷题目列表
    setTopicList([
      ...(data?.exerciseScores ?? []).map((i) => ({
        ...i,
        id: i?.exerciseId,
        code: i?.exerciseCode,
        question: i?.exerciseInfo,
        type: TopicType.Operation,
      })),
      ...(data?.questionScores ?? []).map((i: any) => ({
        ...i,
        code: i?.questionCode,
        type: TopicType.Objective,
        id: i?.questionId,
        question: i?.questionStem,
      })),
    ]);
  };
  useAsyncEffect(getExamResult, []);

  return (
    <>
      {examResult?.studentName && (
        <ProDescriptions
          title={`${examResult?.studentName}考试成绩`}
          dataSource={{ ...examResult }}
          columns={[
            {
              title: "考试班级",
              key: "text",
              render: (_, data) => {
                return `${data.classGrade}年级${data.classTeam}队${data.classUnit}区队`;
              },
            },
            {
              title: "所属课程",
              key: "text",
              dataIndex: "courseName",
            },
            {
              title: "学生名称",
              key: "text",
              dataIndex: "studentName",
            },
            {
              title: "试卷名称",
              key: "text",
              dataIndex: "paperName",
            },
            {
              title: "教师开始考试时间",
              key: "text",
              dataIndex: "planStartTime",
            },
            {
              title: "学生考试开始时间",
              key: "text",
              dataIndex: "studentStartTime",
            },
            {
              title: "学生交卷时间",
              key: "text",
              dataIndex: "studentSubmitTime",
            },
            {
              title: "考生总分",
              key: "text",
              dataIndex: "totalScore",
            },
            {
              title: "教师名称",
              key: "text",
              dataIndex: "teacherName",
            },
          ]}
        ></ProDescriptions>
      )}
      <ProTable<TopicItem>
        loading={loading}
        className="mt-[10px]"
        defaultSize="small"
        rowKey="rowKey"
        pagination={false}
        toolBarRender={false}
        search={false}
        columns={topicItemColumns}
        dataSource={paperData}
      />
    </>
  );
}

interface ExamResultType {
  examDetailId: number;
  score: number;
  max: number;
  onFinish: () => void;
}
const EditScore = ({ score, examDetailId, max, onFinish }: ExamResultType) => {
  const [form] = Form.useForm<{ score: number }>();

  useEffect(() => {
    form.setFieldsValue({ score });
  }, []);

  return (
    <ModalForm<{
      score: number;
    }>
      title={
        <div>
          编辑分数(本题分值为： <span className="text-red-800">{max}</span>分)
        </div>
      }
      trigger={
        <Button type="primary">
          <EditFilled />
          编辑分数
        </Button>
      }
      form={form}
      autoFocusFirstInput
      modalProps={{
        width: 400,
        destroyOnClose: true,
        onCancel: () => console.log("run"),
      }}
      onFinish={async (values) => {
        await request.sgks.examEditExamScoreCreate({
          examDetailId,
          score: values.score,
        });
        onFinish();
        return true;
      }}
    >
      <ProFormDigit
        label=""
        name="score"
        min={0}
        // max={max}
        fieldProps={{ precision: 0 }}
        rules={[
          { required: true, message: "请输入分数" },
          {
            validator: (_, value) => {
              if (value > max) {
                return Promise.reject(new Error(`分数不能超${max}`));
              }
              return Promise.resolve();
            },
          },
        ]}
      />
    </ModalForm>
  );
};
